/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.admin.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.ReplyTemplate;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.ReplyTemplateService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of showing the
 * group detail administration page,then set the corresponding attributes for
 * output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class ReplyTemplateAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1905711543518916918L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int NOT_LOGGED = 2;

	// utility constants

	public static final String ADD = "add";
	public static final String DEL = "del";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		boolean notLogged = (Boolean) request
				.getAttribute(PageConstants.NOTLOGGED);
		if (notLogged)
			return NOT_LOGGED;

		if (isAdmin) {

			return ACCESS_ALLOWED;
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (NOT_LOGGED == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_REPLYTEMPLATES;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (ACCESS_ALLOWED == validationResult) {
			addReplyTemplate(request);
			delReplyTemplate(request);
			getReplyTemplates(request);
		}
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	private void addReplyTemplate(HttpServletRequest request) {

		String cmd = request.getParameter(PageConstants.CMD);
		if (ADD.equals(cmd)) {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(Messages.SESSION_USER);
			if (user == null)
				return;

			String tid = request.getParameter(PageConstants.TID);
			String lang = (String) session.getAttribute(Messages.LANG);
			ReplyTemplate replyTemplate = new ReplyTemplate();
			ReplyTemplateService replyService = new ReplyTemplateService();

			String content = request.getParameter(PageConstants.CONTENT);
			if (tid != null && !Symbols.BLANK.equals(tid.trim()))
				replyTemplate.setTid(new Integer(tid));
			else
				replyTemplate.setTid(new Integer(0));
			replyTemplate.setContent(content);
			replyTemplate.setUserName(user.getUserName());
			replyTemplate.setAddtime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
			replyService.save(replyTemplate);
			String msg = null;
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);
		}

	}

	private void delReplyTemplate(HttpServletRequest request) {

		String cmd = request.getParameter(PageConstants.CMD);
		if (DEL.equals(cmd)) {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(Messages.SESSION_USER);
			if (user == null)
				return;

			String id = request.getParameter(PageConstants.ID);
			String lang = (String) session.getAttribute(Messages.LANG);

			ReplyTemplateService replyService = new ReplyTemplateService();
			if (id != null && !Symbols.BLANK.equals(id.trim())) {
				ReplyTemplate replyTemplate = replyService
						.findById(new Integer(id));
				if (replyTemplate != null)
					replyService.deleteSingle(replyTemplate);
			}

			String msg = null;
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.MSG_SUCCESS);
			} else {
				msg = Messages.getLabel(Messages.MSG_SUCCESS);
			}
			request.setAttribute(Messages.MSG, msg);
		}

	}

	private void getReplyTemplates(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(Messages.SESSION_USER);
		if (user == null)
			return;
		UserService userService = new UserService();
		String tid = request.getParameter(PageConstants.TID);
		int intpageid = 1;
		ReplyTemplateService replyService = new ReplyTemplateService();

		int unit = 10;
		long all;
		int begin, pagenums;
		String pageid = request.getParameter(PageConstants.PAGEID);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		if (tid != null && !Symbols.BLANK.equals(tid.trim()))
			all = replyService.findSizeByProperty(PageConstants.TID,
					new Integer(tid));
		else
			all = replyService.findSizeByProperty(PageConstants.TID,
					new Integer(0));
		pagenums = (int) ((all + unit - 1) / unit);
		begin = unit * (intpageid - 1);
		List<ReplyTemplate> templates = null;
		if (tid != null && !Symbols.BLANK.equals(tid.trim())) {
			TopicService topicService=new TopicService();
			Integer intTid=new Integer(tid);
			Topic topic=topicService.findById(intTid);
			if(topic!=null){
				request.setAttribute(PageConstants.TOPIC, topic);
				GroupService groupService=new GroupService();
				Group group=groupService.findById(topic.getGid());
				if(group!=null){
					request.setAttribute(PageConstants.GROUP, group);
				}
				
			}
			templates = replyService.findByProperty(PageConstants.TID,
					intTid, begin, unit);
		} else {
			templates = replyService.findByProperty(PageConstants.TID,
					new Integer(0), begin, unit);
		}
		if (templates != null) {
			for (ReplyTemplate replyTemplate : templates) {
				User toUser = userService.findByUserName(replyTemplate
						.getUserName());
				if (toUser != null)
					request.setAttribute(replyTemplate.getUserName()
							+ PageConstants.AVATAR_POSTFIX, toUser.getAvatar());
				;
			}
		}
		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;

		request.setAttribute(PageConstants.START_PID, startpid);
		request.setAttribute(PageConstants.END_PID, endpid);

		request.setAttribute("replyTemplates", templates);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.UNIT, unit);
		request.setAttribute(PageConstants.INTPAGEID, intpageid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.GROUP_ADMIN);
		return namespaces;
	}

}
